package com.zb.frame.base.exception;

import com.zb.frame.base.model.R;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  捕抓控制层 Exception
 * </p>
 *
 * @author bangZZ
 * @since 2020-06-04
 */
@RestControllerAdvice
public class CommonExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(CommonExceptionHandler.class);

    /**
     * 自定义异常
     */
    @ExceptionHandler(SelfDefineException.class)
    public R handlerCustomException(SelfDefineException e, HttpServletRequest request) {
        logger.warn("用户操作失败！" + e.getMsg(), e.getMessage());
        return R.error(e.getCode(), "用户操作失败！",e.getMsg());
    }

    /**
     * Shiro 资源权限异常-权限不足
     */
    @ExceptionHandler(UnauthorizedException.class)
    public R handleUnauthorizedException(UnauthorizedException e){
        logger.warn("访问资源被拒，权限不足！" + e.getMessage());
        return R.error(403,"","访问资源被拒，权限不足！");
    }

    /**
     * Shiro 资源权限异常-错误
     */
    @ExceptionHandler(AuthorizationException.class)
    public R handleAuthorizationException(AuthorizationException e){
        logger.warn("授权资源验证失败！" + e.getMessage());
        return R.error("授权资源验证失败！");
    }

    /**
     *Shiro 登录认证-错误
     * @param e
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public R handleAuthenticationException(AuthenticationException e){
        logger.warn("登录认证错误！" + e.getMessage());
        return R.error("登录认证错误！");
    }

    /**
     * 处理其它未知异常
     */
//    @ExceptionHandler(Throwable.class)
//    public R handlerException(Throwable e) {
//        logger.error("服务器内部错误！", e.getMessage());
//        return R.error(500, "服务器内部错误！", e.getMessage());
//    }
}
